import numpy as np
from PyQt4 import QtCore
import sys,os,inspect
sys.path.insert(0,os.path.abspath(os.path.join(os.getcwd(), os.pardir)))## add root path 
from KModel.KSingleStock import KSingleStock
from KModel.KSingleStockDataProcessor import KSingleStockDataProcessor as kprocesser
from KModel.KSingleStockCursor import KSingleStockCursor 
from KTrade.KStockFeed import KStockFeed
from KTrade.KBaseStrategy import KBaseStrategy
from KIndicators.K_MA import K_MA
from KTrade.KHolding import KHolding
from KTrade.KStrategyMetric.KBaseMetric import *
import matplotlib.pyplot as plt
import importlib
import KTrade.KStrategyMetric.KBaseMetric

class KStrategy2SMACross(KBaseStrategy):
	def __init__(self,parent,stockfeed):
		super(KStrategy2SMACross,self).__init__(parent,stockfeed)
		closeds=self.stockfeed.GetAllBars('close')

		self.sma1=K_MA.calculateSMA(closeds,7)
		self.sma2=K_MA.calculateSMA(closeds,21)
		

		
	def OnStart(self):
		# called before test started
		print('starting 2SMA strategy')
	def OnFinish(self):
		# call after test exectued
		print('finishing 2SMA strategy')
	def OnNewBars(self,curfeedindex):
		# called whenever new bar is generated, barobj is a Series object		

		# call base class method, must be called as a first step in this method		
		KBaseStrategy.OnNewBars(self,curfeedindex)
		
		
		ma1val=self.sma1[curfeedindex]
		ma2val=self.sma2[curfeedindex]
		closep=self.stockfeed.GetBarByIndex(curfeedindex,'close')
		symbol=self.stockfeed.GetSymbolName()
		hasTrade=False


		
		# decide trade or not
		if not np.isnan(ma1val) and not np.isnan(ma2val):
			[sharsnum,curtype]=self.position.GetHoldingCountAndType(symbol)
			if ma1val>ma2val:
				if curtype!=KHolding.HoldType.LONG:
					maxshare=self.position.GetMaxSharesCanBuy(symbol,closep)
					if self.position.EnterLong(symbol,closep,maxshare):
						print('buy %d of shares at %.2f$' %(maxshare,closep))
						hasTrade=True
			else:
				if curtype==KHolding.HoldType.LONG:
					if self.position.ExitLong(symbol,closep,sharsnum):
						print('sell %d of shares at %.2f$' %(sharsnum,closep))
						hasTrade=True
			if hasTrade:
				profit=self.position.GetCurrentProfit()*100
				print('current profit is %.2f%%' %(profit))
				
	





def TestRun():

	m_stock=KSingleStock() # create its stock object
	m_stock.SetTick('us','nasdaq','bidu')	
	m_feed=KStockFeed(m_stock)
	m_stratgy=KStrategy2SMACross(None,m_feed)
	m_stratgy.run()
	print(m_stratgy.GetAllMetrics())
	
	return
	plt.figure()
	m_stratgy.sma1.plot()
	m_stratgy.stockfeed.GetDataFrame()['close'].plot()
	plt.show()

if __name__ == "__main__":
	TestRun()